package middleware

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
	"taobao/api/internal/types"
	"taobao/api/pkg"
)

type TokenMiddleware struct {
}

func NewTokenMiddleware() *TokenMiddleware {
	return &TokenMiddleware{}
}

func (m *TokenMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// TODO generate middleware implement function, delete after code implementation
		token := r.Header.Get("token") //获取前端的token
		fmt.Print("触发中间件")
		fmt.Print(token)
		//判断token是否为空
		if token == "" {
			res := &types.RegMsgResponse{ //创建一个局部变量
				Cre:  -1,
				Mag:  "token为空",
				Data: nil,
			}
			httpx.OkJsonCtx(r.Context(), w, res) //???
			return
		}
		// Passthrough to next handler if need

		//判断token是否有效
		tokenString, err := pkg.TokenString(token)
		if err != nil {
			res := &types.RegMsgResponse{ //创建一个局部变量
				Cre:  -2,
				Mag:  err.Error(),
				Data: nil,
			}
			httpx.OkJsonCtx(r.Context(), w, res) //???
			return
		}
		fmt.Print("值.................." + tokenString)
		val := context.WithValue(r.Context(), "ID", tokenString)
		next(w, r.WithContext(val))
	}

}
